# -*-coding:utf-8 -*-
# __author__=LuLu
import pytest
from selenium import webdriver
import os
import allure
from comment.readYaml import ReadYaml
from comment.Tools import sleep

# 声明为fixture(测试准备/清理)方法
_driver = None


@pytest.fixture(scope='session')
@allure.title("公共创建drivers")
def drivers(request):
    global _driver
    if _driver is None:
        _driver = webdriver.Chrome(ReadYaml().get_chrome_driver_path(), options=ReadYaml().is_headless())

    def end():
        sleep(1)
        _driver.quit()

    # 最终执行完
    request.addfinalizer(end)
    return _driver


"""
.代表通过的用例
F代表失败的用例
E代表异常的用例
>>>>>修改测试状态标识，通过√，不通过×
"""


def pytest_report_teststatus(report, config):
    '''
    turn . into √，turn F into x
    '''
    if report.when == 'call' and report.failed:
        return (report.outcome, '---------------------【x】---------------------\n', 'failed')
    if report.when == 'call' and report.passed:
        return (report.outcome, '---------------------【√】---------------------\n', 'passed')


# 失败截图钩子，修改pytest，自定义函数

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    获取每个用例状态的钩子函数
    :param item:
    :param call:
    :return:
    '''
    # 获取钩子方法的调用结果
    outcome = yield
    rep = outcome.get_result()
    # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        # 添加allure报告截图
        if hasattr(_driver, "get_screenshot_as_png"):
            with allure.step('添加失败截图...'):
                allure.attach(_driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
